<template>
    <el-form @submit.prevent="handleAddProduct">
        <!-- 商品标题 -->
        <el-form-item label="商品标题" required>
            <el-input v-model="newProduct.title" placeholder="请输入标题" />
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格" required>
            <el-input-number v-model="newProduct.price" :precision="2" :min="0" controls-position="right" />
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述">
            <el-input v-model="newProduct.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>

        <!-- 商品库存 -->
        <el-form-item label="库存数量" required>
            <el-input-number v-model="newProduct.stock" :min="0" />
        </el-form-item>

        <!-- 分类ID -->
        <el-form-item label="分类ID" required>
            <el-select v-model="newProduct.categoryid" placeholder="请选择分类">
                <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
            </el-select>
        </el-form-item>

        <!-- 是否在售 -->
        <el-form-item label="是否在售">
            <el-switch v-model="newProduct.onsale" />
        </el-form-item>

        <!-- 商品主图上传 -->
        <el-form-item label="商品主图" required>
            <el-upload v-model:file-list="productImageFile" :auto-upload="false" :on-change="handleProductImage"
                accept="image/*">
                <el-button type="primary">选择文件</el-button>
            </el-upload>
        </el-form-item>

        <!-- 广告图上传（可选） -->
        <el-form-item label="广告图">
            <el-upload v-model:file-list="adImageFile" :auto-upload="false" :on-change="handleAdImage" accept="image/*">
                <el-button type="primary">选择文件</el-button>
            </el-upload>
        </el-form-item>

        <el-button type="primary" native-type="submit">提交</el-button>
    </el-form>
</template>
<script setup>
    import { ref } from 'vue';
    import axios from 'axios';

    const newProduct = ref({
        title: '',
        price: 0,
        description: '',
        stock: 0,
        categoryid: null,
        onsale: false
    });

    const productImageFile = ref(null);
    const adImageFile = ref(null);
    const error = ref('');

    // 处理主图上传
    const handleProductImage = (file) => {
        productImageFile.value = file.raw; // 保存 File 对象
    };

    // 处理广告图上传
    const handleAdImage = (file) => {
        adImageFile.value = file.raw; // 保存 File 对象
    };

    // 提交表单
    const handleAddProduct = async () => {
        try {
            // 1. 基础校验
            if (!newProduct.value.categoryid) {
                error.value = '请选择分类';
                return;
            }
            if (!productImageFile.value) {
                error.value = '请上传商品主图';
                return;
            }

            // 2. 构建 FormData
            const formData = new FormData();

            // 2.1 添加普通字段（字段名必须与后端 Product 类属性完全一致）
            formData.append('title', newProduct.value.title);
            formData.append('price', newProduct.value.price.toString());
            formData.append('description', newProduct.value.description || ''); // 处理空值
            formData.append('stock', newProduct.value.stock.toString());
            formData.append('categoryid', newProduct.value.categoryid.toString());
            formData.append('onsale', newProduct.value.onsale ? 'true' : 'false'); // 转换为字符串

            // 2.2 添加文件（字段名必须与 @RequestParam 名称一致）
            formData.append('pimg', productImageFile.value); // 对应后端 @RequestParam("pimg")
            if (adImageFile.value) {
                formData.append('aimg', adImageFile.value); // 对应后端 @RequestParam("aimg")
            }

            // 3. 发送请求
            const response = await axios.post('http://101.201.67.153:9101/product/addProduct', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data' // 显式声明，避免边界问题
                }
            });

            // 4. 处理响应
            if (response.data.code === 1) {
                console.log('商品添加成功:', response.data);
                // 清空表单
                newProduct.value = {
                    title: '',
                    price: 0,
                    description: '',
                    stock: 0,
                    categoryid: null,
                    onsale: false
                };
                productImageFile.value = null;
                adImageFile.value = null;
            } else {
                error.value = response.data.msg || '添加失败';
            }
        } catch (err) {
            // 5. 错误处理
            console.error('请求失败:', err.response?.data);
            error.value = err.response?.data?.error || '网络请求异常';
        }
    };
</script>